<template>
  <el-container id="message-subscribe-detail">
    <el-main>
      <el-container>
        <el-header>
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/message/subscribe' }">订阅消息</el-breadcrumb-item>
              <el-breadcrumb-item>{{type === 'add' ? '新增消息' : '编辑消息'}}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </el-header>
      </el-container>
      <el-form :model="subscribeMsg" :rules="rules" ref="subscribeMsg" label-width="100px" class="demo-subscribeMsg">
        <el-form-item label="名称" prop="scriptName">
          <el-input v-model="subscribeMsg.scriptName" @change="onScriptNameChange" placeholder="请输入名称，最大15个汉字"></el-input>
        </el-form-item>
        <el-form-item label="推送时间" prop="delaySeconds">
          <el-input v-model="subscribeMsg.delaySeconds" @change="onDelaySecondsChange" type="number" placeholder="请输入延迟推送时间（秒）"></el-input>
        </el-form-item>
        <el-form-item label="推送范围" prop="pushRange">
          <el-radio-group v-model="subscribeMsg.pushRange">
            <el-radio label="ACTIVE_48">48库</el-radio>
            <el-radio label="INACTIVE_48">未激活群库的48库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择群库" prop="groupCollectionId" v-show="subscribeMsg.pushRange === 'INACTIVE_48'">
          <el-col :span="6">
            <el-select value-key="value" v-model="subscribeMsg.groupCollectionId" @change="onInActiveIdChange" placeholder="推送方式">
              <el-option v-for="item in gcList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="状态" prop="valid">
          <el-switch
            v-model="subscribeMsg.valid"
            active-text="生效"
            inactive-text="失效"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="消息" prop="pushMessageTypeCode">
          <el-radio-group v-model="subscribeMsg.pushMessageTypeCode">
            <el-radio label="TEXT">文字</el-radio>
            <el-radio label="IMAGE">图片</el-radio>
            <el-radio label="MPNEWS">图文</el-radio>
            <el-radio label="VOICE">语音</el-radio>
            <!--<el-radio label="DYNAMIC_ADDRESS">动态地址</el-radio>-->
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="subscribeMsg.pushMessageTypeCode === 'TEXT'">
          <div id="word-edit"></div>
        </el-form-item>
        <el-form-item v-show="subscribeMsg.pushMessageTypeCode === 'IMAGE'">
         <el-upload
            :headers="uploadHeader"
            class="openid-upload"
            :action="wxImageMsgUploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleImageRemove"
            :on-success="handleUploadImageOK"
            :before-remove="beforeRemove"
            :before-upload="beforeImageUpload"
            list-type="picture"
            :file-list="wxImageFileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">{{imgLimitTip}}</div>
          </el-upload>
        </el-form-item>
        <el-form-item v-show="subscribeMsg.pushMessageTypeCode === 'MPNEWS'">
          <el-row>
            <el-col :span="12">
              <el-upload
                :headers="uploadHeader"
                class="openid-upload"
                :action="wxMpNewsContentImageUploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleMpNewsImageRemove"
                :on-success="handleUploadMpnewsImageOK"
                :before-remove="beforeRemove"
                :before-upload="beforeImageUpload"
                :on-exceed="handleExceed"
                list-type="picture"
                :file-list="wxMpMewsContentImageFileList">
                <el-button size="small" type="primary">点击上传图文消息内置图片</el-button>
                <div slot="tip" class="el-upload__tip upload__tip">微信图文消息中使用的图片需要先上传微信服务器，获取到mediaUrl之后才能在微信图文消息中使用图片的url链接，只允许上传jpeg，jpg，png格式图片文件，大小不超过2mb</div>
              </el-upload>
            </el-col>
            <el-col :span="12" class="media-wap">
              <div v-for="item in mpnewsImages" :key="item.mediaId" class="media-info">
                <div class="media-id">
                  <el-input placeholder="mediaId" v-model="item.mediaId">
                    <template slot="prepend">mediaId: </template>
                  </el-input>
                </div>
                <div class="media-url">
                  <el-input placeholder="mediaUrl" v-model="item.url">
                    <template slot="prepend">mediaUrl: </template>
                  </el-input>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-form-item>
            <el-row>
              <el-input type="text" v-model="subscribeMsg.mpNews.title" placeholder="请输入标题"></el-input>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-row>
              <el-upload
                :headers="uploadHeader"
                class="openid-upload"
                :action="wxImageMsgUploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleMpNewsThumbImageRemove"
                :on-success="handleUploadMpnewsThumbImageOK"
                :before-remove="beforeRemove"
                :before-upload="beforeImageUpload"
                :on-exceed="handleExceed"
                list-type="picture"
                :file-list="wxMpMewsThumbImageFileList">
                <el-button size="small" type="primary">点击上传图文消息封面缩略图</el-button>
                <div slot="tip" class="el-upload__tip">{{imgLimitTip}}</div>
              </el-upload>
            </el-row>
          </el-form-item>
            <div id="image-word-edit"></div>
          <el-form-item style="margin-bottom: 22px;">
            <el-row>
              <el-input type="text" v-model="subscribeMsg.mpNews.contentSourceUrl" placeholder="请输入URL"></el-input>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="4">
                <el-button type="primary" @click="uploadWXArticle">上传图文消息</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form-item>
        <el-form-item v-show="subscribeMsg.pushMessageTypeCode === 'VOICE'">
         <el-upload
            :headers="uploadHeader"
            class="openid-upload"
            :action="wxVoiceMsgUploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleVoiceRemove"
            :before-remove="beforeRemove"
            :before-upload="beforeVoiceUpload"
            :limit="1"
            :on-success="handleUploadVoiceOK"
            :on-error="handleUploadError"
            :on-exceed="handleExceed"
            :file-list="wxVoiceFileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">{{voiceLimitTip}}</div>
          </el-upload>
        </el-form-item>
        <!--<el-form-item v-show="subscribeMsg.pushMessageTypeCode === 'DYNAMIC_ADDRESS'">-->
          <!--<el-input type="text" v-model="subscribeMsg.pushContents.DYNAMIC_ADDRESS" placeholder="请输入动态地址"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="预览">
          <el-input v-model="preview.openid" placeholder="请输入预览者的openid"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="submitPreview">预览</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script>
import E from 'wangeditor';
import { mapActions, mapState } from 'vuex';
import op from 'object-path';
import _ from 'underscore';

import CONSTANT from '../../../constant/common';
import auth from '../../../util/auth';
/* eslint-disable */
const imgSizeLimit = 2000000;
const voiceSizeLimit = 2000000;
const imgTypeLimit = ['image/jpeg', 'image/png', 'image/jpg'];
const voiceTypeLimit = ['audio/mp3'];

const openIdsReg = /(,|\.|\n|\r\n)/g;
const defaultSubscribeMsg = {
  scriptName: '',
  delaySeconds: 0,
  pushRange: '',
  groupCollectionId: '',
  pushMessageTypeCode: '',
  valid: true,
  pushContents: {
    TEXT: '',
    IMAGE: '',
    MPNEWS: '',
    VOICE: '',
    // DYNAMIC_ADDRESS: '',
  }, // text type is content, others are mediaId.
  mpNews: {
    thumbMediaId: '',
    title: '',
    content: '',
    contentSourceUrl: '',
    digest: '',
  },
};
// const TYPE_IS_EDIT = 'edit';
const TYPE_IS_ADD = 'add';

export default {
  props: ['id', 'type'],
  data() {
    const validatePushRange = (rule, value, callback) => {
      callback();
    };
    const validatePushMsgType = (rule, value, callback) => {
      if (value === 'TEXT' && !this.subscribeMsg.pushContents.TEXT) {
        callback(new Error('请输入文字消息'));
      } else if (value === 'IMAGE' && !this.subscribeMsg.pushContents.IMAGE) {
        callback(new Error('请上传图片消息'));
      } else if (value === 'MPNEWS' && !this.subscribeMsg.pushContents.MPNEWS) {
        callback(new Error('请先上传图文消息'));
      } else if (value === 'VOICE' && !this.subscribeMsg.pushContents.VOICE) {
        callback(new Error('请先上传音频消息'));
      } else {
        callback();
      }
    };
    const validateGroupCollectionId = (rule, value, callback) => {
      if (!value && this.subscribeMsg.pushRange === 'INACTIVE_48') {
        callback(new Error('请选择一个群库'));
      }
      callback();
    };
    return {
      imgLimitTip: '只允许上传jpeg，jpg，png格式图片文件，大小不超过2mb',
      voiceLimitTip: '只允许上传MP3格式的文件，大小不超过 2MB',
      mpnewsImages: [],
      textEditor: null,
      mpNewsEditor: null,
      uploadHeader: {
        Authorization: auth.getToken(),
      },
      wxImageFileList: [],
      wxTextImageFileList: [],
      wxVoiceFileList: [],
      wxMpMewsContentImageFileList: [],
      wxMpMewsThumbImageFileList: [],
      preview: {
        openid: '',
      },
      subscribeMsg: {
        ...defaultSubscribeMsg,
        pushContents: {
          TEXT: '',
          IMAGE: '',
          MPNEWS: '',
          VOICE: '',
          // DYNAMIC_ADDRESS: '',
        },
        mpNews: {
          thumbMediaId: '',
          title: '',
          content: '',
          contentSourceUrl: '',
          digest: '',
        },
      },
      rules: {
        scriptName: [
          { required: true, message: '请输入订阅脚本名称', trigger: 'blur' },
          {
            max: 15, message: '最大15个汉字以内', trigger: 'blur',
          },
        ],
        delaySeconds: [
          { required: true, message: '请输入延迟推送时间', trigger: 'blur' },
        ],
        pushRange: [
          { required: true, message: '请选择推送范围', trigger: 'change' },
          { validator: validatePushRange, trigger: 'change' },
        ],
        groupCollectionId: [
          { validator: validateGroupCollectionId, trigger: 'change' },
        ],
        pushMessageTypeCode: [
          { required: true, message: '请选择推送消息类型', trigger: 'change' },
          { validator: validatePushMsgType, trigger: 'change' },
        ],
      },
    };
  },
  watch: {
    id(nv, ov) {
      if (nv || ov) {
        this.getSubscribeMessage({
          appid: this.appId,
          id: this.id,
        });
      }
    },
    type(nv) {
      if (nv === TYPE_IS_ADD) {
        this.subscribeMsg = {
          ...defaultSubscribeMsg,
          pushContents: {
            TEXT: '',
            IMAGE: '',
            MPNEWS: '',
            VOICE: '',
            // DYNAMIC_ADDRESS: '',
          },
          mpNews: {
            thumbMediaId: '',
            title: '',
            content: '',
            contentSourceUrl: '',
            digest: '',
          },
        };
      }
    },
    editInfo(nv) {
      if (!_.isEmpty(nv)) {
        const info = nv;
        console.log('editinfo ', info);
        if (info.pushMessageTypeCode === 'TEXT' && this.textEditor) {
          this.textEditor.txt.html(info.pushContent.replace(/(\r\n)/g, '<br>'));
          this.$notify({
            title: '注意',
            message: '编辑模式下，修改推送内容后，请务必再次预览编辑后的信息内容，防止格式错误。',
            type: 'warning',
          });
        }
        if (info.pushMessageTypeCode === 'MPNEWS' && this.mpNewsEditor) {
          this.getMpNewsByMediaId({
            appid: this.appId,
            mediaId: info.pushContent,
          }).then((res) => {
            const {
              thumbUrl, content, contentSourceUrl, thumbMediaId, title, digest,
            } = op.get(res, 'articles.0');
            this.subscribeMsg = {
              ...this.subscribeMsg,
              mpNews: {
                thumbMediaId,
                title,
                content,
                contentSourceUrl,
                digest,
              },
            };
            this.mpNewsEditor.txt.html(content.replace(/data-src/g, 'src'));
            this.wxMpMewsThumbImageFileList = [{ url: thumbUrl }];
          });
        }
        if (info.pushMessageTypeCode === 'IMAGE') {
          this.getImageByMediaId({
            appid: this.appId,
            mediaId: info.pushContent,
          }).then((blobData) => {
            const ret = window.URL.createObjectURL(blobData);
            this.wxImageFileList = [{ url: ret }];
          });
        }
        if (info.pushMessageTypeCode === 'VOICE') {
          this.getVoiceByMediaId({
            appid: this.appId,
            mediaId: info.pushContent,
          }).then((blobData) => {
            const ret = window.URL.createObjectURL(blobData);
            this.wxVoiceFileList = [{ name: '音频文件', url: ret }];
          });
        }
        this.subscribeMsg = {
          scriptName: info.scriptName || '',
          delaySeconds: +info.delaySeconds || 0,
          pushRange: info.pushRange || '',
          groupCollectionId: info.groupCollectionId || '',
          valid: info.valid,
          pushMessageTypeCode: info.pushMessageTypeCode || '',
          pushContents: {
            TEXT: (info.pushMessageTypeCode === 'TEXT' && info.pushContent) || '',
            IMAGE: (info.pushMessageTypeCode === 'IMAGE' && info.pushContent) || '',
            MPNEWS: (info.pushMessageTypeCode === 'MPNEWS' && info.pushContent) || '',
            VOICE: (info.pushMessageTypeCode === 'VOICE' && info.pushContent) || '',
            // DYNAMIC_ADDRESS: (info.pushMessageTypeCode === 'DYNAMIC_ADDRESS' && info.pushContent) || '',
          }, // text type is content, others are mediaId.
          mpNews: {
            thumbMediaId: '',
            title: '',
            content: '',
            contentSourceUrl: '',
            digest: '',
          },
        };
      }
    },
  },
  computed: {
    ...mapState({
      app48openIds: state => state.message.app48openIds,
      editInfo: state => state.message.subscribeMsg,
      gcList: state => state.group.groupCollectionAppIdList,
    }),
    appId() {
      const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
        JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
      return this.$store.state.woa.currentWoa.appId || localWoa.appId;
    },
    wxImageMsgUploadUrl() {
      return `${CONSTANT.REQUEST_URL}/api/message/${this.appId}/uploadImage`;
    },
    wxMpNewsContentImageUploadUrl() {
      return `${CONSTANT.REQUEST_URL}/api/message/${this.appId}/uploadImageForArticle`;
    },
    wxVoiceMsgUploadUrl() {
      return `${CONSTANT.REQUEST_URL}/api/message/${this.appId}/uploadVoice`;
    },
    msgId() {
      return this.id;
    },
  },
  components: {
  },
  mounted() {
    // set word-input
    this.textEditor = new E('#word-edit');
    this.mpNewsEditor = new E('#image-word-edit');
    // 自定义菜单配置
    this.textEditor.customConfig.zIndex = 2000;
    this.mpNewsEditor.customConfig.zIndex = 2000;
    this.textEditor.customConfig.menus = [
      'link',
    ];
    this.textEditor.customConfig.onchange = this.setTextContent.bind(this);
    this.mpNewsEditor.customConfig.onchange = this.setMpNewsContent.bind(this);

    this.textEditor.create();
    this.mpNewsEditor.create();
    // 获取48库
    this.get48openIds(this.appId);
    // 通过appid 获取群库列表
    this.getGroupCollectionByAppId(this.appId);
    if (this.id) {
      this.getSubscribeMessage({
        appid: this.appId,
        id: this.id,
      });
    }
  },
  methods: {
    ...mapActions([
      'previewMessage',
      'uploadMpNewsMessage',
      'addSubscribeMessage',
      'updateSubscribeMessage',
      'get48openIds',
      'getGroupCollectionByAppId',
      'getSubscribeMessage',
      'getMpNewsByMediaId',
      'getImageByMediaId',
      'getVoiceByMediaId',
    ]),
    onInActiveIdChange(v) {
      this.subscribeMsg.groupCollectionId = v;
    },
    onScriptNameChange(v) {
      this.subscribeMsg.scriptName = v;
    },
    onDelaySecondsChange(v) {
      this.subscribeMsg.delaySeconds = +v;
    },
    setMpNewsContent(text) {
      console.log('setMpNewsContent before ', text);
      // text = text.replace(/(<\/p><p>|<br>|\r\n|\r)/g, '\n').replace(/(<\/p>|<p>|&nbsp;)/g, '');
      console.log('setMpNewsContent ', text);
      this.subscribeMsg.mpNews.content = text;
    },
    setTextContent(text) {
      console.log('setTextContent before ', text);
      text = text.replace(/(<p><br><\/p>)|((<br>)?<\/p>((p><br><\/p>)+)?<p>)/g, '\r\n')
        .replace(/<br>/g, '\r\n')
        .replace(/(<\/p>|<p>|&nbsp;|<div>|<\/div>)/g, '')
        .replace(/target="_blank"/g, '');
      console.log(text);
      this.subscribeMsg.pushContents.TEXT = text;
      this.$refs.subscribeMsg.validateField('pushMessageTypeCode');
    },
    uploadWXArticle() {
      const {
        thumbMediaId, title, content, contentSourceUrl, digest,
      } = this.subscribeMsg.mpNews;
      if (!title) {
        return this.$message.error('请先上传图文消息标题');
      }
      if (!thumbMediaId) {
        return this.$message.error('请先上传图文消息封面缩略图');
      }
      if (!content) {
        return this.$message.error('请先上传图文消息内容');
      }
      const data = {
        appid: this.appId,
        thumbMediaId,
        title,
        content,
        contentSourceUrl,
        digest,
      };
      return this.uploadMpNewsMessage(data).then((res) => {
        this.$message({
          type: 'success',
          message: '图文消息上传成功',
        });
        this.subscribeMsg.pushContents.MPNEWS = op.get(res, 'mediaId');
        this.$refs.subscribeMsg.validateField('pushMessageTypeCode');
      });
    },
    beforeImageUpload(file) {
      console.log('file beforeimageupload ', file);
      const { size, type } = file;
      if (size > imgSizeLimit || imgTypeLimit.indexOf(type) === -1) {
        this.$message({
          type: 'error',
          message: this.imgLimitTip,
        });
        return false;
      }
      return true;
    },
    beforeVoiceUpload(file) {
      console.log('file beforeVoiceUpload ', file);
      const { size, type } = file;
      if (size > voiceSizeLimit || voiceTypeLimit.indexOf(type) === -1) {
        this.$message({
          type: 'error',
          message: this.voiceLimitTip,
        });
        return false;
      }
      return true;
    },
    submitForm() {
      const {
        scriptName, delaySeconds, pushRange, groupCollectionId,
        pushMessageTypeCode, valid, pushContents,
      } = this.subscribeMsg;
      const submitProcess = () => {
        const data = {
          scriptName,
          delaySeconds,
          pushRange,
          groupCollectionId: pushRange === 'ACTIVE_48' ? '' : groupCollectionId,
          pushMessageTypeCode,
          valid,
          pushContent: pushContents[pushMessageTypeCode],
          appid: this.appId,
          id: this.id,
        };
        if (this.id) {
          this.updateSubscribeMessage(data).then(() => {
            this.$message({
              type: 'success',
              message: '编辑订阅消息成功!',
            });
            this.$router.push({
              path: '/message/subscribe',
            });
          }, (e) => {
            this.$message({
              type: 'error',
              message: `编辑保存订阅消息失败->${e.message}`,
            });
          });
        } else {
          this.addSubscribeMessage(data).then(() => {
            this.$message({
              type: 'success',
              message: '创建订阅消息成功!',
            });
            this.$router.push({
              path: '/message/subscribe',
            });
          }, (e) => {
            this.$message({
              type: 'error',
              message: `创建订阅消息失败->${e.message}`,
            });
          });
        }
      };

      this.$refs.subscribeMsg.validate().then(submitProcess);
    },
    resetForm() {
      this.subscribeMsg = {
        ...defaultSubscribeMsg,
        pushContents: {
          TEXT: '',
          IMAGE: '',
          MPNEWS: '',
          VOICE: '',
          // DYNAMIC_ADDRESS: '',
        },
        mpNews: {
          thumbMediaId: '',
          title: '',
          content: '',
          contentSourceUrl: '',
          digest: '',
        },
      };
    },
    handleUploadOpenidOK(res, file) {
      const reader = new FileReader();
      reader.readAsText(file.raw, 'UTF-8');
      reader.onload = (evt) => {
        const fileString = evt.target.result;
        const openIds = fileString.replace(openIdsReg, ' ').split(' ');
        this.subscribeMsg.designatedOpenIdsFile = openIds;
      };
    },
    handleUploadError(err) {
      const respStr = err.message;
      try {
        const resp = JSON.parse(respStr);
        if (resp.status === 451) {
          this.$message.error(resp.message || '上传失败，请检查文件格式大小是否有误。');
        }
      } catch (e) {
        this.$message.error(respStr || '上传失败，请检查文件格式大小是否有误。');
      }
    },
    handleUploadImageOK(res, files, fileList) {
      const mediaId = op.get(res, 'data.mediaId');
      this.subscribeMsg.pushContents.IMAGE = mediaId;
      this.$refs.subscribeMsg.validateField('pushMessageTypeCode');
      if (fileList.length > 1) {
        fileList.shift();
      }
    },
    handleImageRemove() {
      this.subscribeMsg.pushContents.IMAGE = '';
      this.$refs.subscribeMsg.validateField('pushMessageTypeCode');
    },
    handleUploadVoiceOK(res) {
      const mediaId = op.get(res, 'data.mediaId');
      this.subscribeMsg.pushContents.VOICE = mediaId;
      this.$refs.subscribeMsg.validateField('pushMessageTypeCode');
    },
    handleVoiceRemove() {
      this.subscribeMsg.pushContents.VOICE = '';
      this.$refs.subscribeMsg.validateField('pushMessageTypeCode');
    },
    handleUploadMpnewsImageOK(res, file, fileList) {
      if (res.status !== 200) {
        return;
      }
      console.log('handleUploadMpnewsImageOK', res, file, fileList);
      this.mpnewsImages = [...this.mpnewsImages, {
        ...res.data,
        uid: file.uid,
      }];
    },
    handleMpNewsImageRemove(file, fileList) {
      console.log('handleMpNewsImageRemove', file, fileList);
      this.mpnewsImages = _.reject(this.mpnewsImages, v => v.uid === file.uid);
    },
    handleUploadMpnewsThumbImageOK(res) {
      const mediaId = op.get(res, 'data.mediaId');
      this.subscribeMsg.mpNews.thumbMediaId = mediaId;
    },
    handleMpNewsThumbImageRemove() {
      this.subscribeMsg.mpNews.thumbMediaId = '';
    },
    handleUploadDynamicImageOK(res, file, files) {
      console.log('handleUploadDynamicImageOK', res, file, files);
    },
    submitPreview() {
      const msgType = this.subscribeMsg.pushMessageTypeCode;

      let content = '';
      let mediaId = '';
      if (msgType === 'TEXT') {
        content = this.subscribeMsg.pushContents[msgType];
      } else {
        mediaId = this.subscribeMsg.pushContents[msgType];
      }

      const data = {
        msgType,
        content,
        mediaId, // 'dsQPSwtRtCaQI4gqzN2b7bVPsidgEDN09AsQYTB7JcE',
        appid: this.appId,
        toWxUserName: '',
        toWxUserOpenid: this.preview.openid, // || 'oH5LRwkv-MVZ4r5jlw0dCTfBNLwY',
      };

      if (!this.preview.openid) {
        return this.$message({
          type: 'error',
          message: '请输入预览者openId',
        });
      }
      if (msgType === 'TEXT' && !content) {
        return this.$message({
          type: 'error',
          message: '请先输入文本消息',
        });
      }
      // if (!content) {
      //   return this.$message({
      //     type: 'error',
      //     message: '请先输入动态消息',
      //   });
      // }
      if ((msgType !== 'TEXT') && !mediaId) {
        return this.$message({
          type: 'error',
          message: '请先上传图文&图片&语音消息',
        });
      }

      return this.previewMessage(data).then((resp) => {
        if (resp.errorCode && resp.errorCode === '1') {
          this.$message({
            type: 'error',
            message: `${resp.errorMsg || '发送预览失败，请稍后再试或者联系管理员'}`,
          });
        } else {
          this.$message({
            type: 'success',
            message: '发送预览成功',
          });
        }
      }, (e) => {
        this.$message({
          type: 'error',
          message: `发送预览失败->${e.message}`,
        });
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove() {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>

<style lang="less" scoped>
#message-subscribe-detail {
  .breadcrumb {
    height: 40px;
  }
  #image-word-edit, #word-edit {
    margin-bottom: 22px;
  }
  .media-wap {
    margin-top: 180px;
  }
  .media-info {
    height: 102px;
    line-height: 25px;
  }
  .upload__tip {
    height: 120px;
  }
}
</style>
